package com.education.welco.service.impl;

import com.education.welco.mapper.StudyResoursesDetailMapper;
import com.education.welco.pojo.StudyResoursesDetail;
import com.education.welco.service.StudyResoursesDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class StudyResoursesDetailServiceImpl implements StudyResoursesDetailService {

    @Autowired
    private StudyResoursesDetailMapper studyResoursesDetailMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(StudyResoursesDetail studyResoursesDetail) {
        studyResoursesDetail.setTopCatalogId(getTopCataLogId(studyResoursesDetail.getCatalogId()));
        StudyResoursesDetail detail = studyResoursesDetailMapper.selectByParam(studyResoursesDetail);
        if (Objects.nonNull(detail) && (detail.getDuration() < studyResoursesDetail.getDuration())) {
            studyResoursesDetail.setId(detail.getId());
            studyResoursesDetailMapper.updateByPrimaryKey(studyResoursesDetail);
        }
        if (Objects.isNull(detail)) {
            studyResoursesDetailMapper.insert(studyResoursesDetail);
        }
    }

    //获取顶级id
    private Integer getTopCataLogId(Integer catalogId) {
        Integer parentCatalogId = studyResoursesDetailMapper.getTopCatalogId(catalogId);
        if (!parentCatalogId.equals(null) && !parentCatalogId.equals(0)) {
            return getTopCataLogId(parentCatalogId);
        }
        return catalogId;
    }
}
